package com.apple;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.Socket;

@Slf4j
@Component
@RequiredArgsConstructor
public class SocketClient {
    private final Socket client;

    public void send(String message){
        OutputStream outputStream = getOutputStream();
        InputStream inputStream = getInputStream();

        PrintWriter printWriter = new PrintWriter(outputStream, true);

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        printWriter.println(message);
        log.info("客户端发送：{}",message);

        String response = getResponse(bufferedReader);
        log.info("socket服务端返回：{}",response);
    }

    public String getResponse(BufferedReader bufferedReader){
        String response=null;
        try {
            response = bufferedReader.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return response;
    }

    public OutputStream getOutputStream(){
        OutputStream outputStream = null;

        try {
            outputStream = client.getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return outputStream;
    }
    
    public InputStream getInputStream(){
        InputStream inputStream=null;
        try {
            inputStream = client.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return inputStream;
    }
}
